<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/7/23
 * Time: 13:37
 */

namespace app\admin\controller;

use think\Db;
use think\Request;
use org\Qiniu;
class Goodsps extends Base
{
    /**
     * 消息首页展示
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax ()){
            $params = input('param.');
            $where = [
                'good_status' => ['<>',3]
            ];
            //状态
            if(isset($params['n_range']) && $params['n_range'] != ''){
                if($params['n_range'] == 3){
                    $where['good_status'] = 1;
                    $where['good_stock'] = ['<=',0];
                }else{
                    $where['good_status'] = $params['n_range'];
                }

            }
            if(isset($params['pic']) && $params['pic'] != ''){
                if($params['pic'] == 1){
                    $where['good_thumb'] = ['like','%panson%'];
                }else{
                    $where['good_thumb'] = null;
                }

            }
            // 名字
            if(isset($params['n_title']) && $params['n_title'] != ''){
                $where['good_name|good_coding'] = ['like', '%' . $params['n_title'] . '%'];
            }
            // 名字
            if(isset($params['schoolid']) && $params['schoolid'] != ''){
                $goodids = Db::table('up_school_good')
                    ->where('sg_school_erp',$params['schoolid'])
                    ->group('sg_good_coding')
                    ->column('sg_good_coding');
                $where['good_coding'] = ['in',$goodids];
            }
            
            $Nowpage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'g.*,school_name,school_id';
            $count = Db::table('up_goods')->alias('g')
                ->join('up_school s','g.good_school=s.school_id','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_goods')->alias('g')
                ->join('up_school s','g.good_school=s.school_id','LEFT')
                ->where($where)
                ->page($Nowpage,$limits)
                ->order('good_update_time desc')
                ->field($field)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $schools = Db::table('up_school')
            ->where('school_id','>',0)
            ->field('school_erp,school_name')
            ->select();
        $this->assign('schools',$schools);
        return $this->fetch();
    }

    
    /**
     * 商品详情
     * @return mixed
     */
    public function goodInfo(){
        $g_id = input('good_id');
        $data = Db::table('up_goods')
            ->where('good_id',$g_id)
            ->find();
        $spec = Db::table('up_good_spec')
            ->where('spec_good_id',$g_id)
            ->field('spec_size,spec_size_two')
            ->select();
        $this->assign([
            'data' => $data,
            'spec' => $spec,
        ]);
        return $this->fetch('goodsps/goodinfo');
    }
    /**
     * 编辑商品
     * @return mixed|\think\response\Json
     */
    public function goodEdit(){
        if(Request::instance()->isPost()){
            Db::startTrans();
            try{
                $params = input('param.');
                $time = date('Y-m-d H:i:s');
                $data = [
                    'good_name' => trim($params['good_name'], ' '), // 标题
                    'good_thumb' => $params['good_thumb'],// 内容
                    'good_image' => $params['good_image'],// 内容
                    'good_content' => $params['content'],// 内容
                    'good_update_time' => $time, // 推送时间
                ];
                $goods_id = $params['good_id'];
                Db::table('up_goods')->where('good_id',$goods_id)->update($data);
                Db::commit();
                return json(['code' => 200, 'msg' => '更新成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '更新失败']);
            }
        }
        $g_id = input('good_id');
        $data = Db::table('up_goods')
            ->where('good_id',$g_id)
            ->find();

        $this->assign([
            'data' => $data,
        ]);
        return $this->fetch('goodsps/goodedit');
    }

    /**
     * 设置尺码
     * @return mixed|\think\response\Json
     */
    public function setSizes(){
        if(Request::instance()->isPost()){
            Db::startTrans();
            try{
                $params = input('param.');
                $goods_id = $params['good_id'];
                $sizes = trim($params['sizes'], ',');
                $twos = trim($params['twos'], ',');
                if(!$sizes || !$twos){
                    return json(['code' => 100, 'msg' => '不能为空']);
                }
                $sizes = explode(',',$sizes);
                $twos = explode(',',$twos);
                if(count($sizes) != count($twos)){
                    return json(['code' => 100, 'msg' => '尺码数和对应值数不一致！']);
                }
                $good = Db::table('up_goods')->where('good_id',$goods_id)->field('good_coding,good_coding_less')->find();
                $insert = [];
                foreach ($sizes as $k => $v){
                    $insert[] = [
                        'spec_size' => $v,
                        'spec_size_two' => $twos[$k],
                        'spec_good_coding' => $good['good_coding'],
                        'spec_good_coding_less' => $good['good_coding_less'],
                        'spec_good_id' => $goods_id
                    ];
                }
                Db::table('up_good_spec')->where('spec_good_id',$goods_id)->delete();
                Db::table('up_good_spec')->insertAll($insert);
                Db::commit();
                return json(['code' => 200, 'msg' => '更新成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '更新失败']);
            }
        }
        $g_id = input('good_id');
        $specSize = Db::table('up_good_spec')
            ->where('spec_good_id',$g_id)
            ->order('spec_size asc')
            ->column('spec_size');
        $specTwo = Db::table('up_good_spec')
            ->where('spec_good_id',$g_id)
            ->order('spec_size asc')
            ->column('spec_size_two');
        $this->assign([
            'good_id' => $g_id,
            'specSize' => implode($specSize,','),
            'specTwo' => implode($specTwo,','),
        ]);
        return $this->fetch('goodsps/setsize');
    }

    /**
     * 查看评价
     * @return mixed|\think\response\Json
     */
    public function goodsComments(){
        if(request()->isAjax()){
            extract(input());
            $good_id = input('good_id');
            $where = [
                'comment_good_id' => $good_id
            ];
            $count = Db::name('goods_comment')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.comment_user_id','left')
                ->join('up_goods g','a.comment_good_id=g.good_id','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('goods_comment')->alias('a')
                ->join('up_u_user uuu','uuu.user_id = a.comment_user_id','left')
                ->join('up_goods g','a.comment_good_id=g.good_id','LEFT')
                ->where($where)
                ->field('a.*,uuu.user_username,uuu.user_phone,good_name')
                ->select();
            if($lists){
                foreach ($lists as $k=>$v){
                    if($v['comment_image']){
                        $lists[$k]['comment_image'] = explode(',',$v['comment_image']);
                    }
                }
            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $good_id = input('good_id');
        $this->assign('good_id',$good_id);
        return $this->fetch('goodsps/goodscomments');
    }
    /**
     * 改状态
     * @author
     */
    public function changeGoodStatus()
    {
        extract(input());
        $res = Db::table('up_goods')
            ->where('good_id',$id)
            ->update([
                'good_update_time' => date('Y-m-d H:i:s'),
                'good_status' => $num
            ]);
        if($res){
            return json(['code' => 200, 'msg' => '成功']);
        }else{
            return json(['code' => 100, 'msg' => '失败']);
        }
    }
    /**
     * 导入Excel
     * @return mixed
     */
//    public function excelIn(){
//        set_time_limit(0);
//        if(request()->file('file')){
//            $file = request()->file('file');
//            $info  = $file->getInfo();
//            $file_path = $info['tmp_name'];
//            //取出文件后缀
//            $file_type = explode(".",$info['name']);
//            $file_type = end($file_type);
//            vendor("PHPExcel.PHPExcel.IOFactory");
//            if( $file_type == 'xls' ){
//                $inputFileType = 'Excel5';    //这个是读 xls的
//            }else{
//                $inputFileType = 'Excel2007';//这个是计xlsx的
//            }
//            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
//            $objPHPExcel = $objReader->load($file_path);
//            $objWorksheet = $objPHPExcel->getActiveSheet();
//            $highestRow = $objWorksheet->getHighestRow();
////            print_r($highestRow);die;
//            $time = date('Y-m-d H:i:s');
//            $stra = '';
//            for ($i=1;$i<=$highestRow;$i++) {
//                $a = $objPHPExcel->getActiveSheet ()->getCell ("A" . $i)->getValue ();//老款号
//                if($a != ''){
//                    $stra .= $a . ',';
//                }
//            }
//            dump($stra);
//            die;
//            echo '/admin/Goodsps/index';
//        }
//        return $this->fetch('goodsps/excelin');
//    }
    public function excelIn(){
        set_time_limit(0);
        if(request()->file('file')){
            $file = request()->file('file');
            $dir = ROOT_PATH . 'public' . DS . 'uploads/zip';
            if(!file_exists($dir)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($dir, 0700,true);
            }
            $time = date('Ymd');
            $time22 = time();
            $file_root = $file->getPathname();
            $zip = new \ZipArchive;//新建一个ZipArchive的对象
            $res = $zip->open($file_root);//打开zip
            //读取zip
            if($res === TRUE){
                $newDir = $dir . '/' . $time . '/' . $time22;
                $zip->extractTo($newDir);//将zip包解压到指定目录
                $zip->close();
                $file = $this->wenjian($newDir);//递归查询文件夹下的文件 （如果zip包中是单个的文件就不需要遍历文件夹，只需要处理对应的文件即可）
                //处理相对应的的文件
               // dump($file);die;
			   $url =  http_type ();
                foreach ($file as $kk => $vv){
					$url2 = '/uploads/zip/' . $time . '/' . $time22 . '/' . $kk . '/';
					foreach ($vv as $k => $v){
						if(count($v) >= 1){
							$kuan = $k;
							$kuanImg = $v[0];
							if(count($v) == 1){
								$lunboImg = $url . $url2 . $k . '/' . $kuanImg;
							}elseif(count($v) == 2){
								unset($v[0]);
								$lunboImg = $url . $url2 . $k . '/' . implode($v,',');
							}else{
								$lunboImg = implode($v,',' . $url . $url2 . $k . '/');
								$lunboImg = explode(',',$lunboImg);
								unset($lunboImg[0]);
								$lunboImg = implode($lunboImg,',');
							}
							Db::table('up_goods')
								->where('good_coding',$kuan)
								->update([
									'good_thumb' => $url . $url2 . $k . '/' . $kuanImg,
									'good_update_time' => date('Y-m-d H:i:s'),
									'good_image' => $lunboImg
								]);
						}
						
					}
                }
            }
            echo '/admin/Goodsps/index';
        }
        return $this->fetch('goodsps/excelin');
    }
    //遍历文件
    public function wenjian($dir)
    {
        $files = array();
        if(@$handle = opendir($dir)) { //注意这里要加一个@，不然会有warning错误提示：）
            while(($file = readdir($handle)) !== false) {
                if($file != ".." && $file != ".") { //排除根目录;
                    if(is_dir($dir."/".$file)) { //如果是子文件夹，就进行递归
                        $files[$file] = $this->wenjian($dir."/".$file);
                    } else { //不然就将文件的名字存入数组;
                        $files[] = $file;
                    }

                }
            }
            closedir($handle);
            return $files;
        }
    }
    /**
     * 导入Excel
     * @return mixed
     */
    public function excelIn2(){
        set_time_limit(0);
        if(request()->file('file')){
            $file = request()->file('file');
            $info  = $file->getInfo();
            $file_path = $info['tmp_name'];
            //取出文件后缀
            $file_type = explode(".",$info['name']);
            $file_type = end($file_type);
            vendor("PHPExcel.PHPExcel.IOFactory");
            if( $file_type == 'xls' ){
                $inputFileType = 'Excel5';    //这个是读 xls的
            }else{
                $inputFileType = 'Excel2007';//这个是计xlsx的
            }
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($file_path);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
//            print_r($highestRow);die;
            $time = date('Y-m-d H:i:s');
            $data = [];
            for ($i=2;$i<=$highestRow;$i++) {
                $a = $objPHPExcel->getActiveSheet ()->getCell ("E" . $i)->getValue ();//款号
                $b = $objPHPExcel->getActiveSheet ()->getCell ("A" . $i)->getValue ();//学校
                $c = $objPHPExcel->getActiveSheet ()->getCell ("I" . $i)->getValue ();//年份
                $d = $objPHPExcel->getActiveSheet ()->getCell ("J" . $i)->getValue ();//性别
                $e = $objPHPExcel->getActiveSheet ()->getCell ("O" . $i)->getValue ();//校标
                $f = $objPHPExcel->getActiveSheet ()->getCell ("M" . $i)->getValue ();//增不加
                if($b != '' && $d != ''){
                    $sex = 2;
                    if($d == '男'){
                        $sex = 1;
                    }
                    $inser = [
                        'sg_school_erp' => $b,
                        'sg_good_coding' => $a,
                        'sg_good_coding_less' => substr($a,1,12),
                        'sg_good_q' => 1,
                        'sg_sign' => $e,
                        'sg_year' => $c,
                        'sg_sex' => $sex,
                        'good_price' => $f,
                        'sg_time' => $time,
                        'sg_updatetime' => $time
                    ];
                    $inser2 = [
                        'sg_school_erp' => $b,
                        'sg_good_coding' => $a,
                        'sg_good_q' => 1,
                        'sg_sign' => $e,
                        'sg_year' => $c,
                        'sg_sex' => ['in',"$sex,3"]
                    ];
                    $have = Db::table('up_school_good')->where($inser2)->find();
                    if(empty($have)){
                        $data[] = $inser;
                    }
                }
            }
            if($data){
                $res = Db::table('up_school_good')->insertAll($data);
                if($res){
                    echo '/admin/Goodsps/index';
                }else{
                    echo '/admin/Goodsps/excelin2';
                }
            }else{
                echo '/admin/Goodsps/index';
            }
        }
        return $this->fetch('goodsps/excelin2');
    }
    /**
    /**
     * 导入Excel
     * @return mixed
     */
    public function excelInOld(){
        set_time_limit(0);
        if(request()->file('file')){
            $file = request()->file('file');
            $info  = $file->getInfo();
            $file_path = $info['tmp_name'];
            //取出文件后缀
            $file_type = explode(".",$info['name']);
            $file_type = end($file_type);
            vendor("PHPExcel.PHPExcel.IOFactory");
            if( $file_type == 'xls' ){
                $inputFileType = 'Excel5';    //这个是读 xls的
            }else{
                $inputFileType = 'Excel2007';//这个是计xlsx的
            }
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            $objPHPExcel = $objReader->load($file_path);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
//            print_r($highestRow);die;
            $time = date('Y-m-d H:i:s');
            for ($i=2;$i<=$highestRow;$i++) {
                $a = $objPHPExcel->getActiveSheet ()->getCell ("A" . $i)->getValue ();//老款号
                $b = $objPHPExcel->getActiveSheet ()->getCell ("B" . $i)->getValue ();//新款号
                $c = $objPHPExcel->getActiveSheet ()->getCell ("C" . $i)->getValue ();//品名
                $d = $objPHPExcel->getActiveSheet ()->getCell ("D" . $i)->getValue ();//地址
                if($b != '' && $d != ''){
                    $data = Db::table('up_goods')
                        ->where('good_coding',$b)
                        ->field('good_id,good_thumb,good_image')
                        ->find();
                    if($data){
                        $updata = array();
                        if(empty($data['good_thumb']) || empty($data['good_image'])){

                            $path = $d;
                            $endtype = explode('.',$path);
                            $type = end($endtype);
                            $rand = time() . rand(100000,999999);
                            $image_name = ROOT_PATH . 'public' . DS . 'uploads/images/'.$rand.'.'.$type;
                            $ch = curl_init ($path);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                            curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
                            $img = curl_exec ($ch);
                            curl_close ($ch);
                            try{
                                //$image_name就是要保存到什么路径,默认只写文件名的话保存到根目录
                                $fp = fopen($image_name,'w');//保存的文件名称用的是链接里面的名称
                                fwrite($fp, $img);
                                fclose($fp);
                                //
                                //组装图片名
                                $key = md5(time().uuid()).'.'.$type;
                                $up = new Qiniu();
                                $res = $up->uploadFile($image_name,$key);
                                $d = config('qiniu.domain') . $res;
                                unlink($image_name);
                            }catch(\Exception $e){
                                $d = '';
                            }
                        }
                        if(empty($data['good_thumb'])){
                            $updata['good_thumb'] = $d;
                        }
                        if(empty($data['good_image'])){
                            $updata['good_image'] = $d;
                        }
                        if($updata){
                            //更新
                            Db::table('up_goods')->where('good_coding', $b)->update($updata);
                        }
                    }
                }
            }
        }
        return $this->fetch('goodsps/excelin');
    }
    /**
     * 批量导出（待定，之前的消息导出）
     * @return \think\response\Json
     */
    //导出
    public function excelOut()
    {
        set_time_limit(0);//防止超时
        //ini_set("memory_limit", "512M");//防止内存溢出
        extract(input());
        $params = input('param.');
        $where = [
            'good_status' => ['<>',3]
        ];
        //状态
        if(isset($params['n_range']) && $params['n_range'] != ''){
            if($params['n_range'] == 3){
                $where['good_status'] = 1;
                $where['good_stock'] = ['<=',0];
            }else{
                $where['good_status'] = $params['n_range'];
            }

        }
        if(isset($params['pic']) && $params['pic'] != ''){
            if($params['pic'] == 1){
                $where['good_thumb'] = ['like','%panson%'];
            }else{
                $where['good_thumb'] = null;
            }

        }
        // 名字
        if(isset($params['n_title']) && $params['n_title'] != ''){
            $where['good_name|good_coding'] = ['like', '%' . $params['n_title'] . '%'];
        }
        // 名字
        if(isset($params['schoolid']) && $params['schoolid'] != ''){
            $goodids = Db::table('up_school_good')
                ->where('sg_school_erp',$params['schoolid'])
                ->group('sg_good_coding')
                ->column('sg_good_coding');
            $where['good_coding'] = ['in',$goodids];
        }
        // id
        if(isset($params['ids']) && $params['ids'] != ''){
            $where['good_id'] = ['in',$params['ids']];
        }
        $field = [
            'good_name,good_coding,good_sex,good_pinming,good_price,good_type,good_status,good_create_time,good_thumb'
        ];
        $data = Db::table('up_goods')->alias('g')
            ->join('up_school s','g.good_school=s.school_id','LEFT')
            ->where($where)
            ->field($field)
            ->select();
        if($data){
            $cellname = [
                '名字', '款号', '款号性别', '品名','价格', '类型', '状态','新建时间', '图片地址'
            ];
            $status = ['good_status'];
            $values = [
                'good_status' => [1 => '正常',2 => '冻结'],
                'good_sex' => [1 => '男',2 => '女',3 => '通用'],
            ];
            $res = exportExcel('goods',time(),$cellname,$data,$status,$values);
            return json($res);
        }else{
            return json(['code'=>0,'msg'=>'此条件下无数据']);
        }
    }
}